#!/bin/bash

set -e

. /usr/share/debconf/confmodule

# This will be replaced with debian/zentyal-core.scripts-common which includes
# helper functions to set the password
#SCRIPTSCOMMON#

# ask zentyal port
conf_port() {
    while true; do

        db_input high zentyal-core/port || true
        db_go || true

        db_get zentyal-core/port
        new_port="$RET"

        # check if the entry is valid port number
        nodigits="$(echo $new_port | sed 's/[[:digit:]]//g')"
        if [ -n "$nodigits" ]; then
            continue
        fi

        if [ $new_port -ge 65535 ] || [ $new_port -lt 1 ]; then
            continue;
        fi

        if ! check_port_available $new_port; then
           db_input high zentyal-core/port_used || true
           db_go || true
           db_get zentyal-core/port_used
            if [ "$RET" = "true" ]; then
                break;
            fi
        else
            break;
        fi
    done
}

# check non-existance of ebox user as a normal user
EBOX_UID=`getent passwd ebox | cut -d: -f3`
if [ -n "$EBOX_UID" ] && [ $EBOX_UID -ge 1000 ]
then
    db_input high zentyal-core/user_exists || true
    db_go || true
    exit 1
fi

if [ "$1" = reconfigure ] || [ -z "$2" ]; then
    conf_port
fi

exit 0
